package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 为了获取Session 强转ServletReqest为HttpServletRequest 因为doGet和doPost的那个request是HttpServletRequest，这个没Http的是根接口，是他的父类
        HttpServletRequest req = (HttpServletRequest) request;
        //1.判断session中是否有user
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            //登录过了
            //放行
            chain.doFilter(request, response);
        } else {
            //没有登录，添加错误提示，跳转到登录页面
            req.setAttribute("login_msg", "您尚未登录！");
            req.getRequestDispatcher("/login.jsp").forward(req, response);
            //弹幕说：CSS也被Filter拦截了
        }


    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
